package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.AdvertisementActivity.TimeCount;
import com.ihighest.app.infox.adapter.ChooseProvincesAdapter;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.LoopListener;
import com.ihighest.app.infox.tools.LoopView;
import com.ihighest.app.infox.tools.RegexKit;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 申请成为专家
 * 
 * @author lkx Created at 2015-11-16 上午11:59:33
 * @version 1.0
 */
public class ApplyBeSpecialist extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
	private ActivityTitle title;
	private LinearLayout rootview;
	private RelativeLayout.LayoutParams layoutParams;
	private PopupWindow mPopupWindow;
	private LoopView loopView;
	private String a;
	RadioButton male, female;
	private EditText name, phoneNumber, goodCrops, weixinNumber, address, qqNumber, Email, workUnit, job, memo, specialistVerificationCode;
	private TextView specialistType, goodAtArea;
	/* 头像名称 */
	private Bitmap myBitmap;
	private static final String PHOTO_FILE_NAME = "specialistphoto.jpg";
	private File tempFile;
	private Uri photoUri;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private ImageView cardPositive, cardnNegative;
	private int image;// 选中的是正面还是反面的标识，0表示正面，1标识反面
	private ApiParam param;
	File fTemp1 = null;// 正面临时文件
	File fTemp2 = null;// 反面临时文件
	static Bitmap bitmap = null;
	private String gender = "m";// 性别，默认为男

	private String codeId;// 验证码id
	private int time;// 倒计时时间
	private TextView getcode;
	private TimeCount timer;
	private ArrayList<String> specialistTypes = new ArrayList<String>();
	private JSONArray array;
	private boolean isEmail = true;
	public static List<String> mAddress = new ArrayList<String>();// 擅长地区id
	public static List<String> mGoodArea = new ArrayList<String>();// 擅长地区

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_acivity_apply_specialist);
		initView();
	}

	/**
	 * 初始化
	 * 
	 * 
	 * @author lkx Created at 2015-10-13 下午2:20:35
	 */
	private void initView() {
		title = (ActivityTitle) findViewById(R.id.infox_ApplyForSpecialistActivity_title);
		title.setTitle("申请成为专家");
		param = ApiParam.create();
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("提交");
		male = (RadioButton) findViewById(R.id.rbMale);
		female = (RadioButton) findViewById(R.id.rbFemale);
		name = (EditText) findViewById(R.id.specialistName);
		phoneNumber = (EditText) findViewById(R.id.specialistPhoneNumber);
		weixinNumber = (EditText) findViewById(R.id.specialistWeixin);
		qqNumber = (EditText) findViewById(R.id.specialistQQ);
		Email = (EditText) findViewById(R.id.specialistEmail);
		workUnit = (EditText) findViewById(R.id.specialistWorkUnit);
		job = (EditText) findViewById(R.id.specialistJob);
		memo = (EditText) findViewById(R.id.specialistMemo);
		specialistType = (TextView) findViewById(R.id.specialistGoodType);
		goodCrops = (EditText) findViewById(R.id.specialistGoodForPlant);
		goodAtArea = (TextView) findViewById(R.id.specialistGoodArea);
		address = (EditText) findViewById(R.id.specialistAddress);
		cardPositive = (ImageView) findViewById(R.id.cardImgFrontage);
		cardnNegative = (ImageView) findViewById(R.id.cardImgback);
		specialistVerificationCode = (EditText) findViewById(R.id.specialistVerificationCode);
		getcode = (TextView) findViewById(R.id.getCode);
		cardPositive.setOnClickListener(this);
		cardnNegative.setOnClickListener(this);
		male.setOnCheckedChangeListener(this);
		female.setOnCheckedChangeListener(this);
		male.setChecked(true);

		param.addParam("sex", gender);
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				judgeData();
			}
		});
		findViewById(R.id.beGoodForAreaLayout).setOnClickListener(this);
		findViewById(R.id.getCode).setOnClickListener(this);
		findViewById(R.id.specialistType).setOnClickListener(this);
		// initData();
		getData();
	}

	/**
	 * 获取数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-17 下午4:42:26
	 */
	private void getData() {
		Api.data("specialist_type_list.json", new ApiCallback(ApplyBeSpecialist.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getDatas() != null || result.getDatas().length() != 0) {
					for (int i = 0; i < result.getDatas().length(); i++) {
						try {
							specialistTypes.add(result.getDatas().getString(i));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub

			}
		}, ApplyBeSpecialist.this);
		Api.data("area_provincial.json", new ApiCallback(ApplyBeSpecialist.this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getDatas() != null || result.getDatas().length() != 0) {
					array = result.getDatas();
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub

			}
		}, ApplyBeSpecialist.this);

	}

	/**
	 * 数据判断
	 * 
	 * 
	 * @author lkx Created at 2015-11-17 下午2:25:36
	 */
	protected void judgeData() {
		if (TextUtils.isEmpty(name.getText().toString()) || TextUtils.isEmpty(specialistType.getText().toString())
				|| TextUtils.isEmpty(goodCrops.getText().toString()) || TextUtils.isEmpty(goodAtArea.getText().toString())
				|| TextUtils.isEmpty(phoneNumber.getText().toString())
				|| TextUtils.isEmpty(specialistVerificationCode.getText().toString())) {
			ToastKit.showShort(ApplyBeSpecialist.this, "请您完善所有必填项信息");

		} else {
			if (fTemp1 == null) {
				ToastKit.showShort(ApplyBeSpecialist.this, "请选择身份证正面照片");
			} else if (fTemp2 == null) {
				ToastKit.showShort(ApplyBeSpecialist.this, "请选择身份证反面照片");
			} else if (TextUtils.isEmpty(memo.getText().toString())) {
				ToastKit.showShort(ApplyBeSpecialist.this, "请输入简介信息");
			} else {

				param.addParam("title", name.getText().toString());
				param.addParam("plants", goodCrops.getText().toString());
				param.addParam("area", listToString(mAddress));
				param.addParam("phone", phoneNumber.getText().toString());
				param.addParam("captcha", specialistVerificationCode.getText().toString());
				param.addParam("captcha_id", codeId);
				param.addParam("specialistType", specialistType.getText().toString());
				param.addParam("memo", memo.getText().toString());

				if (!TextUtils.isEmpty(weixinNumber.getText().toString()))
					param.addParam("wechat", weixinNumber.getText().toString());
				if (!TextUtils.isEmpty(address.getText().toString()))
					param.addParam("addr", address.getText().toString());
				if (!TextUtils.isEmpty(workUnit.getText().toString()))
					param.addParam("corp", workUnit.getText().toString());
				if (!TextUtils.isEmpty(job.getText().toString()))
					param.addParam("profession", job.getText().toString());
				if (!TextUtils.isEmpty(qqNumber.getText().toString()))
					param.addParam("qq", qqNumber.getText().toString());
				if (!TextUtils.isEmpty(Email.getText().toString())) {
					if (RegexKit.isEmail(Email.getText().toString())) {
						param.addParam("mail", Email.getText().toString());
						isEmail = true;
					} else {
						ToastKit.showShort(ApplyBeSpecialist.this, "请输入正确的邮箱");
						isEmail = false;
					}
				}
				if (isEmail) {
					commitData();
				}

			}
		}

	}

	/**
	 * 提交数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-17 下午2:21:21
	 */
	protected void commitData() {
		if (TextUtils.isEmpty(SharedPreferencesKit.getString(ApplyBeSpecialist.this, Const.SP_KEY_USER_ID))) {
			ToastKit.showShort(ApplyBeSpecialist.this, "您还没有登录");
		} else {
			title.rightText.setClickable(false);
			Api.post("apply/specialist", param, new ApiCallback(ApplyBeSpecialist.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						finish();
					} else {
						ToastKit.showShort(ApplyBeSpecialist.this, result.getMsg());
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					// TODO Auto-generated method stub
					title.rightText.setClickable(true);
				}
			}, ApplyBeSpecialist.this);

		}

	}

	/**
	 * 初始化数据
	 * 
	 * 
	 * @author lkx Created at 2015-10-13 下午4:24:18
	 */
	@SuppressLint("ResourceAsColor")
	private void initData(View v) {
		layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

		rootview = (LinearLayout) v.findViewById(R.id.mRootView);

		loopView = new LoopView(this);
		TextView view = new TextView(ApplyBeSpecialist.this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lp.setMargins(0, 10, 0, 5);
		view.setLayoutParams(lp);
		view.setBackgroundResource(R.drawable.infox_send_back);
		view.setText("确  定");
		view.setTextSize(18.0f);
		view.setPadding(20, 10, 20, 10);
		view.setTextColor(Color.WHITE);
		view.setGravity(Gravity.CENTER);

		// 设置是否循环播放
		loopView.setNotLoop();
		// 滚动监听
		// loopView.setListener(new LoopListener() {
		//
		// @Override
		// public void onItemSelect(int item) {
		// }
		// });
		// 设置原始数据
		loopView.setArrayList(specialistTypes);
		// 设置初始位置
		loopView.setPosition(0);
		// 设置字体大小
		loopView.setTextSize(18.0f);
		rootview.addView(loopView, layoutParams);
		rootview.addView(view);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int selectItem = loopView.selectItem();
				a = specialistTypes.get(selectItem);
				// Toast.makeText(ApplyBeSpecialist.this,
				// specialistTypes.get(selectItem), 0).show();
				specialistType.setText(a);
				mPopupWindow.dismiss();
			}
		});
	}

	/**
	 * 初始化popuwindow
	 * 
	 * 
	 * @author lkx Created at 2015-10-5 上午10:58:08
	 */
	private void initPupoVindow() {
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_pupopwindow_scrollitem_layout, null);
		initData(popupWindow);

		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
	}

	private void showPupop() {
		if (mPopupWindow == null) {
			initPupoVindow();
			mPopupWindow.showAtLocation(ApplyBeSpecialist.this.findViewById(R.id.parentView), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
					0, 0);
		} else {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAtLocation(ApplyBeSpecialist.this.findViewById(R.id.parentView), Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}

		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.beGoodForAreaLayout:
			mGoodArea = new ArrayList<String>();
			mAddress = new ArrayList<String>();
			ChooseDialog dialog = new ChooseDialog(ApplyBeSpecialist.this, R.style.CustomDialog);
			dialog.show();
			break;
		case R.id.specialistType:
			// 专家类型
			showPupop();
			break;
		case R.id.beGoodForPlantLayout:
			// 擅长作物
			showPupop();
			break;

		case R.id.cardImgFrontage:
			image = 0;
			chooseImg();

			break;
		case R.id.cardImgback:
			image = 1;
			chooseImg();

			break;
		case R.id.getCode:
			if (TextUtils.isEmpty(phoneNumber.getText().toString())) {
				ToastKit.showShort(ApplyBeSpecialist.this, "请输入手机号");
			} else
				Api.post("mobilecaptcha",
						ApiParam.create().addParam("phone", phoneNumber.getText().toString()).addParam("type", "specialist"),
						new ApiCallback(this) {

							private long countTime;

							@Override
							public void handleSuccess(ApiResult result) {
								try {
									if (result.getCode() == 100) {
										codeId = result.getData().getString("captcha_id");
										time = Integer.valueOf(result.getData().getString("time"));
										countTime = time * 1000;

										getcode.setClickable(false);
										getcode.setBackgroundResource(R.drawable.infox_register_btn_gettextcode_bg);
									} else {
										ToastKit.showShort(ApplyBeSpecialist.this,
												TextUtils.isEmpty(result.getMsg()) ? "获取验证码失败" : result.getMsg());
									}
								} catch (JSONException e) {
									Log.e(TAG, e.getMessage(), e);
								}
								timer = new TimeCount(countTime, 1000);
								timer.start();
							}

							@Override
							public void handleFailure(Exception e, String msg) {
							}
						}, this);
			break;
		}

	}

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			getcode.setBackgroundResource(R.drawable.infox_content_comment_bg);
			getcode.setText("重新获取");
			getcode.setClickable(true);

		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			getcode.setClickable(false);
			getcode.setText((millisUntilFinished / 1000) + "s后重新获取");

		}
	}

	private void chooseImg() {
		new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

			}
		}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {

				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				// 判断存储卡是否可以用，可用进行存储
				if (hasSdcard()) {
					ContentValues values = new ContentValues();
					photoUri = ApplyBeSpecialist.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
				}
				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
			}
		}).show();
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * 
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				if (tempFile != null) {
					crop(Uri.fromFile(tempFile));
				}

			} else {
				Toast.makeText(ApplyBeSpecialist.this, "未找到存储卡，无法存储照片！", 0).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				if (image == 0) {

					this.cardPositive.setImageBitmap(myBitmap);
				}
				if (image == 1) {
					this.cardnNegative.setImageBitmap(myBitmap);
				}
				upload();
				boolean delete = tempFile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * 
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 图片数据拼接
	 * 
	 * 
	 * @author lkx Created at 2015-10-17 下午2:45:38
	 */
	private void upload() {
		if (myBitmap != null) {
			BufferedOutputStream bos = null;

			try {
				if (image == 0) {// 正面证件照
					System.out.println("正面");
					fTemp1 = File.createTempFile("card", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp1));
				}
				if (image == 1) {// 反面证件照
					System.out.println("反面");
					fTemp2 = File.createTempFile("card2", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp2));
				}
				// fTemp = File.createTempFile("card", ".jpg");

				// BufferedOutputStream bos = new BufferedOutputStream(new
				// FileOutputStream(fTemp));
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (image == 0) {// 正面证件照
				param.addParam("pic1", fTemp1);
			}
			if (image == 1) {// 反面证件照
				param.addParam("pic2", fTemp2);
			}

		}

	}

	@Override
	public void onCheckedChanged(CompoundButton rb, boolean ischeck) {
		if (ischeck) {
			switch (rb.getId()) {
			case R.id.rbMale:
				gender = "m";
				param.addParam("sex", gender);
				break;

			case R.id.rbFemale:
				gender = "f";
				param.addParam("sex", gender);
				break;
			}
		}
	}

	class ChooseDialog extends Dialog {
		private TextView ensure;
		private TextView cancle;
		private ListView datasList;

		public ChooseDialog(Context context, int theme) {
			super(context, theme);
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			setCustomDialog();
		}

		public ChooseDialog(Context context) {
			super(context);
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			setCustomDialog();
		}

		private void setCustomDialog() {

			View mView = LayoutInflater.from(ApplyBeSpecialist.this).inflate(R.layout.infox_acivity_apply_specialis_choosedoalogt, null);
			initView(mView);

			super.setContentView(mView);
		}

		private void initView(View view) {
			ensure = (TextView) view.findViewById(R.id.ensure);
			cancle = (TextView) view.findViewById(R.id.cancle);
			datasList = (ListView) view.findViewById(R.id.dataList);
			ensure.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					goodAtArea.setText(listToString(mGoodArea));
					dismiss();
				}
			});
			cancle.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					dismiss();

				}
			});
			datasList.setAdapter(new ChooseProvincesAdapter(ApplyBeSpecialist.this, array));

		}
	}

	/**
	 * @Description:把list转换为一个用逗号分隔的字符串
	 */
	public static String listToString(List list) {
		StringBuilder sb = new StringBuilder();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (i < list.size() - 1) {
					sb.append(list.get(i) + ",");
				} else {
					sb.append(list.get(i));
				}
			}
		}
		return sb.toString();
	}
}
